// Diapositives d'une séance (contenu structuré) — et PDF original via ?pdf=1. import { NextResponse } from "next/server"; import { createReadStream, existsSync, statSync } from "node:fs"; import { Readable } from "node:stream"; import { resolve } from "node:path"; import { apiError, requireEnrollment } from "@/lib/api.ts"; import { AuthError, requireUser } from "@/lib/auth/session.ts"; import { all, get } from "@/lib/db/index.ts"; import { normalizeCourse } from "@/lib/learning/helpers.ts"; export async function GET(req: Request, ctx: { params: Promise<{ course: string; week: string }> }) { try { const user = await requireUser(); const params = await ctx.params; const course = normalizeCourse(params.course); requireEnrollment(user.id, course); const week = parseInt(params.week, 10); if (!Number.isInteger(week) || week < 1 || week > 14) throw new AuthError(404, "Séance inconnue."); const doc = get<{ id: number; title: string; path: string }>( "SELECT id, title, path FROM documents WHERE course_code = ? AND doc_type = 'slides' AND week = ? AND visible_to_students = 1", course, week ); if (!doc) throw new AuthError(404, "Séance introuvable."); // PDF original compilé (même chemin que la source .tex) if (new URL(req.url).searchParams.get("pdf") === "1") { const pdfPath = resolve(process.cwd(), "..", doc.path.replace(/\.tex$/, ".pdf")); if (!existsSync(pdfPath)) return NextResponse.json({ error: "PDF non disponible pour cette séance." }, { status: 404 }); const size = statSync(pdfPath).size; const stream = Readable.toWeb(createReadStream(pdfPath)) as ReadableStream; return new Response(stream, { headers: { "Content-Type": "application/pdf", "Content-Length": String(size), "Content-Disposition": `inline; filename="${course}-seance${String(week).padStart(2, "0")}.pdf"`, "Cache-Control": "private, max-age=3600", }, }); } const slides = all<{ ref_number: number; title: string; section_title: string; display_content: string; box_types: string }>( `SELECT ref_number, title, section_title, display_content, box_types FROM chunks WHERE document_id = ? AND ref_type = 'slide' ORDER BY ref_number, seq`, doc.id ); return NextResponse.json({ deck: { week, title: doc.title }, slides }); } catch (e) { return apiError(e); } }